export default {
  mounted() {
    // 监听窗口的改变
    window.addEventListener('resize', this.onResize)

    // 创建一个观察器实例并传入回调函数
    // DOM3提供的 Events 规范的一部分
    this.observer = new MutationObserver((mutationsList, observer) => {
      for (let mutation of mutationsList) {
        if (mutation.type === 'attributes') {
          this.onResize()
        }
      }
    })
    // 配置开始观察目标节点
    this.observer.observe(this.$refs.boxRef, {
      attributes: true,
      childList: false,
      subtree: false
    })
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.onResize)
    this.observer.disconnect()
  },
  methods: {
    onResize: throttle(function () {
      // 此方法是echarts提供的，可以重新计算尺寸
      this.myChart.resize()
    })
  }
}

function throttle(func, delay = 300) {
  let timeoutId

  return function () {
    const context = this
    const args = arguments

    if (!timeoutId) {
      timeoutId = setTimeout(function () {
        func.apply(context, args)
        timeoutId = null
      }, delay)
    }
  }
}
